<template>
  <!-- 
    使用此组件需要传递两个对象
    dialog(状态)和fromData(数据)
  -->
  <div class="dialog">
    <el-dialog
      :visible.sync="dialog.show"
      :title="dialog.title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="false"
    >
      <el-form :model="formData" :rules="rules" ref="form">
        <el-form-item label="文章分类" prop="class_name" label-width="90px">
          <el-input v-model="formData.class_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="详情" label-width="90px" prop="detail">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="分类详情"
            v-model="formData.detail"
          >
          </el-input>
        </el-form-item>
        <el-form-item class="dialog-button">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" class="submit" @click="submitForm('form')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rules: {
        className: [{ required: true, message: "必填项", trigger: "blur" }],
      },
      dialogImage: false,
    };
  },
  props: {
    dialog: Object,
    formData: Object,
  },

  methods: {
    //提交时根据dialog里面option的值选择接口
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const url = `${
            this.dialog.option === "edit"
              ? `update/${this.formData.id}`
              : "addclass"
          }`;
          this.$axios
            .post(`/api/class/${url}`, this.formData)
            .then((res) => {
              console.log(res)
              if (res.data.state) {
                this.$message({
                  message: res.data.msg,
                  type: "success",
                });
                //把dialog里面的数据清空
                this.dialog.show = false;
                this.formData.class_name = "";
                this.formData.detail = "";
                //使用自定义事件，再次获取数据，刷新页面。
                this.$emit("getClass");
              } else {
                this.$message({
                  message: res.data.msg,
                  type: "error",
                });
              }
            })
            .catch((err) => console.log(err.message));
        }
      });
    },
    //取消时清空数据并且隐藏dialog
    cancel() {
      this.dialog.show = false;
      this.formData.class_name = "";
      this.formData.detail = "";
    },
  },
};
</script>

<style scoped>

.dialog-button {
  margin-left: 100px;
}
</style>